<template>
  <div class="product">
    <a-card :title="t['商品列表']" class="h-full">
      <template #extra>
        <a-input-search
          v-model="query.goodsName"
          allow-clear
          @search="search"
          @keydown.enter="search"
        />
      </template>
      <div :key="updateKey">
        <a-table
          v-model:selected-keys="selectedProductIds"
          class="mt-2"
          :loading="loading"
          :data="productList"
          :columns="translateColumns(columns)"
          row-key="goodsId"
          :pagination="{
            total: query.total,
            current: query.pageNum,
            pageSize: query.pageSize,
            simple: true
          }"
          @page-change="pageChange"
          @page-size-change="pageSizeChange"
          @row-click="cellClick"
        >
          <template #operational="{ record }">
            <a-badge v-if="selectedProductIds.find((v) => v === record.goodsId)" color="green">
            </a-badge>
          </template>
        </a-table>
        <PreviewProduct :list="selectedProductIds" />
      </div>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { listGoods } from "@/api/service/goods/goods";
import { Goods } from "@/api/service/goods/types";

import { dispatchModal } from "../../data/form";

import columns from "../data/columns";

import { currentGroup, groupIndex, previewToggle, selectedProductIds } from "../data/data";

const t = translate("公共模块");

const productList = ref<Goods[]>();

const updateKey = ref(0);

const loading = ref(false);

const query = useQuery({
  goodsName: "",
  goodsId: "",
  orderByColumn: "goods_id",
  isAsc: "desc",
  pageSize: 15
});

const cellClick = (item: any) => {
  if (selectedProductIds.value.includes(item.goodsId)) {
    selectedProductIds.value = selectedProductIds.value.filter((e) => e !== item.goodsId);
  } else {
    selectedProductIds.value.push(item.goodsId);
  }

  const max = Math.max(...currentGroup.value.items.map((e) => e.groupsIndex));

  if (selectedProductIds.value.length > max) {
    selectedProductIds.value.shift();
  }
  groupIndex.value = selectedProductIds.value.length;
  previewToggle.value += 1;
};

const getList = async () => {
  try {
    loading.value = true;
    const data = await listGoods(query.value);
    productList.value = data.rows;
    query.value.total = data.total;
    loading.value = false;
  } catch (error) {
    loading.value = false;
  }
};

const pageChange = (num: number) => {
  query.value.pageNum = num;
  getList();
};

const pageSizeChange = (num: number) => {
  query.value.pageSize = num;
  getList();
};

const search = () => {
  query.value.pageNum = 1;
  getList();
};

watch(dispatchModal, () => {
  updateKey.value++;
  if (!dispatchModal.value) return;
  getList();
});

watch(selectedProductIds, () => {});
</script>

<style lang="scss" scoped>
.product {
  min-width: 300px;
  flex-basis: 300px;
}
</style>
